package cn.qu.dockman.mgr;

import cn.qu.dockman.mgr.disparte.*;
import cn.qu.dockman.mgr.service.HostService;
import cn.qu.dockman.mgr.ws.SendingQueue;
import cn.qu.dockman.mgr.ws.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * Created by zh on 2017/3/5.
 */
@EnableWebSocket
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter implements WebSocketConfigurer {

    @Bean
    public ServerEndpointExporter createServerEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public HostObserver hostObserver(DispartMgr dispartMgr) {
        return new HostObserver(dispartMgr);
    }

    @Bean
    public PingObserver pingObserver(DispartMgr dispartMgr) {
        return new PingObserver(dispartMgr);
    }

    @Bean
    public ImageListObserver imageListObserver(DispartMgr dispartMgr) {
        return new ImageListObserver(dispartMgr);
    }

    @Bean
    public ContainerListObserver containerListObserver(DispartMgr dispartMgr) {
        return new ContainerListObserver(dispartMgr);
    }

    @Bean
    public NetworkListObserver networkListObserver(DispartMgr dispartMgr) {
        return new NetworkListObserver(dispartMgr);
    }

    @Bean
    public RegisterObserver registerObserver(DispartMgr dispartMgr) {
        return new RegisterObserver(dispartMgr);
    }

    @Bean
    public DispartMgr dispartMgr() {
        return new DispartMgr();
    }

    @Bean
    public SendingQueue sendingQueue(HostService hostService) {
        SendingQueue queue = new SendingQueue();
        queue.setHostService(hostService);
        return queue;
    }

    public static void main(String[] args) {
        new SpringApplication(Application.class).run(args);
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        WebSocketServer socketServer = new WebSocketServer();
        socketServer.setApplicationContext(applicationContext);
        try {
            socketServer.afterPropertiesSet();
        } catch (Exception e) {
            e.printStackTrace();
        }
        registry.addHandler(socketServer, "/websocket");
    }
}
